<?php
class Subscribe_Push_Cron_Checker
{
	public static function main()
	{
		$self = new self();
		//这里的顺序不要变
		$self->_checkStockWithNoMr();
		$self->_checkStockHasZyZsAlert();
		$self->_checkStockOutOfDays();
	}
	
	protected function _checkStockWithNoMr()
	{
		$allStocks = Dzl_Db_Factory::getInstance()
			->createSelect()
			->from('dzl_alert_stocks', '*')
			->where('alive=?', 1)
			->query()
			->fetchAll();
		
		foreach ($allStocks as $stock) {
			if ($stock['mrdate'] == null || $stock['mrdate'] == '0000-00-00') {
				$this->_delectStock($stock['id']);
			}
		}
	}
	
	protected function _checkStockOutOfDays()
	{
		$today = date('Y-m-d');
		$maxDays = Zend_Registry::get('dzlalert')->day->range;
		$allStocks = Dzl_Db_Factory::getInstance()
			->createSelect()
			->from('dzl_alert_stocks', '*')
			->where('alive=?', 1)
			->query()
			->fetchAll();
		
		foreach ($allStocks as $stock) {
			$days = $this->countDate($stock['mrdate'], $today);
			if ($days >= $maxDays) {
				$this->_delectStock($stock['id']);
			}
		}
	}
	
	protected function _checkStockHasZyZsAlert()
	{
		$allStocks = Dzl_Db_Factory::getInstance()
			->createSelect()
			->from('dzl_alert_stocks', '*')
			->where('alive=?', 1)
			->query()
			->fetchAll();
		
		foreach ($allStocks as $stock) {
			if (($stock['zydate'] != null && $stock['zydate'] != '0000-00-00') 
			|| ($stock['zsdate'] != null && $stock['zsdate'] != '0000-00-00')) {
				$this->_delectStock($stock['id']);
			}
		}
	}
	
	protected function _delectStock($id)
	{
		$bind = array('alive' => 0);
		$where = array('id=?' => $id);
		$rtn =  Dzl_Db_Factory::getInstance()
			->createTable('dzl_alert_stocks')
			->update($bind, $where);
	}
	
	public function countDate($startDate, $endDate)
	{
		$hexinTradeDay = Hexin_TradeDay::getInstance();
		$count = 0;
		$indexDate = $startDate;
		while ($indexDate <= $endDate) {
			if ($hexinTradeDay->isTradeDay($indexDate)) {
				$count++;
			}
			$indexDate = date('Y-m-d', strtotime('+1 day', strtotime($indexDate)));
		}
		return $count;
	}
}